<?php

namespace App\Admin\Controllers;

use App\Models\City;
use App\Models\Department;
use App\Models\Family;
use App\Models\Points;
use App\Models\User;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UserController extends Controller
{
    use ModelForm;

    public $header = '用户列表';

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(User::class, function (Grid $grid) {

            $grid->model()->orderBy('id', 'desc');
            $grid->id('编号')->sortable();
            $grid->username('用户名')->editable();
            $grid->mobile('手机号');
            $grid->familyUser()->is_householder('身份')->using([
                '1' => '户主'
            ])->label();
            $grid->department('部门')->pluck('name')->label();
            $grid->gender('性别')->using([
                '0' => '女',
                '1' => '男',
                '2' => '保密',
            ]);
            $grid->birthday('出生日期');
            $grid->created_at('创建时间');

            /*$user_id = $this->id;
                if(!file_exists(public_path('uploads/qrcodes')))
                    mkdir(public_path('uploads/qrcodes'));
                $svg_path = public_path("uploads/qrcodes/$user_id.png");
                if(!file_exists($svg_path))
                    QrCode::format('png')->size(200)->generate(encrypt($user_id), $svg_path);
                return "qrcodes/$user_id.png";*/

            /*$grid->column('二维码')->display(function (){
                return QrCode::generate(base64_encode($this->id));
            });*/

            $grid->points()->points('可用积分');

            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->like('username', '用户名');
                $filter->like('mobile', '手机号');
                $filter->between('created_at', '创建日期')->datetime();
                $filter->between('birthday', '出生日期')->datetime();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(User::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('username', '用户名')->rules('required');
            $form->image('avatar', '头像');

            //$form->cropper('avatar','头像');
            //$form->cropper('avatar','头像')->cRatio(200,200);

            $form->mobile('mobile', '手机号')->rules('required|regex:/^1[345789][0-9]{9}$/');
            $form->radio('gender', '性别')->options(['0'=>'女','1' => '男', '2'=> '保密']);
            $form->datetime('birthday', '生日');
            $form->multipleSelect('department', '部门')
                ->options(Department::all()->pluck('name', 'id'));

            $form->select('province_id','省')->options(
                City::province()->pluck('name', 'id')
            )->load('city_id', '/admin/api/city')->setWidth(4);

            $form->select('city_id','市')->options(function ($city_id) {
                return City::options($city_id);
            })->load('area_id', '/admin/api/area')->setWidth(4);

            $form->select('area_id', '区')->options(function ($area_id) {
                return City::options($area_id);
            })->setWidth(4);

            $states = [
                'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
            ];
            $form->switch('status', '是否启用')->states($states)->default('1');

            $form->display('created_at', '创建时间');
            $form->display('updated_at', '更新时间');

            $form->disableViewCheck();


            //验证手机号是否已使用
            $form->saving(function (Form $form) {
                $user = User::where('mobile', $form->mobile)->first();
                if ($user){
                    $error = new MessageBag([
                        'title'   => '新增失败',
                        'message' => '手机号已存在....',
                    ]);

                    return back()->with(compact('error'));
                }

                //$form->code = uniqid();

            });

            $form->saved(function (Form $form) {

                $points = Points::where('user_id', $form->model()->id)->first();

                if (!$points){
                    $points_initial = 0;

                    $setting = Points\Setting::first();
                    if ($setting){
                        $points_initial = $setting['points_initial'];
                    }
                    $points = new Points;
                    $points->user_id = $form->model()->id;
                    $points->points = $points_initial;
                    $points->save();
                }
            });
        });
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header($this->header)
            ->description('Detail')
            ->body($this->detail($id, $content));
    }

    public function detail($id, Content $content)
    {
        //基本资料 会员信息
        $user_data = User::with('department')
            ->with('family')
            ->where('id',$id)
            ->first()->toArray();

        $user_data['family_users'] = [];
        $user_data['householder'] = [];
        if ($user_data['family']){
            $user_data['family_users'] = Family\User::getFamilyUsers($user_data['family']['family_id']);

            if ($user_data['family_users']){
                foreach ($user_data['family_users'] as $key=>$val){
                    if ($val['is_householder']){
                        $user_data['householder'] = $val;
                        break;
                    }
                }
            }
        }


        if ($user_data){
            $user_data['gender'] = $user_data['gender'] == '0' ? '女' : ($user_data['gender'] == '1') ? '男' : '保密';
        }

        $content->row(view('admin.user.show', $user_data));

    }

}
